<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace app\adminapi\services\maintenance;

use app\dao\maintenance\LangTranslationDao;
use kitego\base\BaseService;
use kitego\services\common\CacheService;
use kitego\utils\VolcengineUtil;
use think\db\exception\DbException;
use think\facade\Db;
use Throwable;

class LangTranslationService extends BaseService
{
    public function __construct(LangTranslationDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 翻译列表
     * @param int $page
     * @param int $pageSize
     * @param mixed $keyWords
     * @param int|null $langId 语言ID
     * @throws DbException
     */
    public function list(int $page, int $pageSize, mixed $keyWords, ?int $langId)
    {
        $where[] = ['is_delete', '=', 0];

        if (!empty($langId)) {
            $where[] = ['lang_id', '=', $langId];
        }

        // 关键词模糊搜索
        $whereOr = [];
        if (isset($keyWords)) {
            $keyWords = trim($keyWords);
            $whereOr = [
                ['original_text', 'like', '%' . $keyWords . '%'],
                ['translation', 'like', '%' . $keyWords . '%']
            ];
        }
        $list = $this->dao->page($where, $whereOr, '*', $page, $pageSize, 'sort desc', ['lang']);

        $newList = [];
        foreach ($list['data'] as $v) {
            $v['langDesc'] = $v['lang']['lang_name'] . '（' . $v['lang']['lang_flag'] . '）';
            $translationList = [
                'translationList' => [[
                    'langId' => $v['lang']['id'],
                    'lang' => $v['langDesc'],
                    'translation' => $v['translation']
                ]]
            ];
            unset($v['lang']);
            $newList[] = array_merge($v, $translationList);
        }
        $list['data'] = $newList;

        return success($list);
    }

    /**
     * 编辑地区
     * @param mixed $id 翻译id
     * @param string $scene 翻译场景
     * @param int $sort 排序值
     * @param string $originalText 原文
     * @param array $translationList 译文列表
     * @param string $isDelete 是否删除
     */
    public function edit(mixed $id, string $scene, int $sort, string $originalText, array $translationList, string $isDelete)
    {
        $data = [];
        foreach ($translationList as $v) {
            // 同语言相同原文不可重复添加
            if (
                empty($id) &&
                $this->dao->find([
                    ['scene', '=', $scene],
                    ['lang_id', '=', $v['langId']],
                    ['original_text', '=', $originalText]
                ])
            ) {
                continue;
            }
            $data[] = [
                'scene' => $scene,
                'lang_id' => $v['langId'],
                'sort' => $sort,
                'original_text' => $originalText,
                'translation' => $v['translation'],
                'is_delete' => $isDelete,
            ];
        }

        $res = Db::transaction(function () use ($id, $data) {

            if (!empty($id)) {
                $res = $this->dao->update($id, $data[0], 'id');
            } else {
                $res = $this->dao->saveAll($data);
            }

            // 清除翻译缓存
            CacheService::clear('translation');

            return $res;
        });

        return success(['data' => $res]);
    }

    /**
     * 批量删除
     * @param array $ids
     * @throws DbException
     */
    public function batchDel(array $ids)
    {
        $this->dao->update([['id', 'in', $ids]], ['is_delete' => 1]);

        return success();
    }

    /**
     * 机器翻译
     * @param string $originalText 原文
     * @param int|null $langId 语言Id
     * @throws Throwable
     */
    public function robotTranslate(string $originalText, ?int $langId = null)
    {
        $langConfig = sys_config('lang');
        if (empty($langConfig['huoAccessKey']) || empty($langConfig['huoSecretKey'])) {
            exception('请先配置火山翻译key');
        }
        $translator = VolcengineUtil::getInstance();
        $translator->setAccessKey($langConfig['huoAccessKey']);
        $translator->setSecretKey($langConfig['huoSecretKey']);

        if (!empty($langId)) {
            $where[] = ['id', '=', $langId];
        } else {
            $where[] = ['status', '=', 1];
            $where[] = ['is_delete', '=', 0];
        }

        // 已生效语言列表
        $langList = app()->make(LangService::class)->getColumn($where, 'lang_name, lang_flag, id', 'id');
        $data = [];
        foreach ($langList as $v) {
            if ($v['lang_flag'] == 'zh-Hant') {
                $lang = 'zh-Hant';
            } else {
                $lang = substr($v['lang_flag'], 0, 2);
            }
            $data[$v['id']] = $translator->translateText('', $lang, [$originalText])[0]['Translation'];
        }

        return success($data);
    }
}